<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart-main"></div>
    <div class="color-legend">
      <div v-for="(item, index) in currentData" :key="index" class="color-block"
        :class="{ 'selected': selectedIndexes.includes(index) }" @click="toggleSelect(index)"
        :title="`${item.name}\n运输量: ${item.value}\n占比: ${item.ratio}%`">
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import axios from "axios";

const selectedIndexes = ref([]);
const toggleSelect = (index) => {
  selectedIndexes.value = selectedIndexes.value.includes(index) ? [] : [index];
  highlightSelected();
};

const chartRef = ref(null);
let chartInstance = null;
let intervalId = null;

const dataGroups = ref([[], []]);
const currentGroupIndex = ref(0);
const currentChartType = ref('pie'); // 'pie', 'bar', 'line'

const currentData = computed(() => {
  return dataGroups.value[currentGroupIndex.value] || [];
});

const getInitial = (name) => {
  return name ? name.charAt(0) : '';
};

const getItemColor = (index) => {
  const colors = ["#80FFA5", "#00DDFF", "#37A2FF", "#FF0087", "#FFBF00"];
  return colors[index % colors.length];
};

const cachedData = ref(null);

const fetchEntryVolumeRatio = async () => {
  if (cachedData.value) {
    dataGroups.value = [cachedData.value, cachedData.value];
    updateChart();
    return;
  }

  try {
    const response = await axios.get("http://localhost:8082/logistics/entryVolumeRatio");
    if (response.data.code === 200 && response.data.data) {
      cachedData.value = response.data.data.map(item => ({
        value: item.volume,
        name: item.company,
        ratio: item.ratio
      }));
      dataGroups.value = [cachedData.value, cachedData.value];
      updateChart();
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  updateChart();
};

const updateChart = () => {
  if (!chartInstance || !currentData.value.length) return;

  let option = {
    backgroundColor: 'rgba(0,0,0,0.2)',
    animation: true,
    animationDuration: 1000,
    animationEasing: 'elasticOut',
    animationDelay: function(idx) {
      return idx * 200;
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        const data = currentData.value[params.dataIndex];
        return `<div style="font-weight:bold">${data.name}</div>
                <div style="margin-top:5px">运输量: <span style="color:#00DDFF">${data.value}</span></div>
                <div>占比: <span style="color:#80FFA5">${data.ratio}%</span></div>`;
      },
      backgroundColor: 'rgba(0, 20, 40, 0.95)',
      borderColor: '#00bfff',
      borderWidth: 2,
      padding: [10, 15],
      textStyle: {
        color: '#fff',
        fontSize: 14
      },
      extraCssText: 'box-shadow: 0 0 10px rgba(0, 191, 255, 0.5);'
    },
    legend: {
      show: false
    },
    color: ["#80FFA5", "#00DDFF", "#37A2FF", "#FF0087", "#FFBF00"]
  };

  // 根据当前图表类型添加不同的系列配置
  switch (currentChartType.value) {
    case 'pie':
      option.series = [{
        name: '运输量占比',
        type: 'pie',
        radius: ['40%', '80%'],
        center: ['50%', '50%'],
        roseType: 'radius',
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2,
          shadowBlur: 15,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        label: {
          show: true,
          formatter: '{b}: {d}%',
          color: '#fff',
          fontSize: 12,
          fontWeight: 'bold'
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 15
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 20,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.7)'
          }
        },
        data: currentData.value
      }];
      break;
    
    case 'bar':
      option.xAxis = {
        type: 'category',
        data: currentData.value.map(item => item.name),
        axisLabel: {
          interval: 0,
          rotate: 45,
          textStyle: {
            color: '#fff'
          }
        }
      };
      option.yAxis = {
        type: 'value',
        axisLabel: {
          textStyle: {
            color: '#fff'
          }
        }
      };
      option.series = [
        {
          name: '运输量',
          type: 'bar',
          barWidth: '50%',
          data: currentData.value.map(item => item.value),
          itemStyle: {
            borderRadius: [8, 8, 0, 0],
            borderWidth: 2,
            borderColor: '#fff',
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#80FFA5' },
              { offset: 1, color: '#00DDFF' }
            ]),
            shadowBlur: 15,
            shadowColor: 'rgba(0, 221, 255, 0.5)'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 20,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 221, 255, 0.7)'
            }
          }
        }
      ];
      break;
    
    case 'line':
      option.polar = {
        radius: ['30%', '70%'],
        center: ['50%', '50%']
      };
      option.angleAxis = {
        type: 'category',
        data: currentData.value.map(item => item.name),
        boundaryGap: false,
        clockwise: true,
        axisLabel: {
          color: '#fff'
        }
      };
      option.radiusAxis = {
        min: 0,
        max: Math.max(...currentData.value.map(item => item.value)) * 1.2,
        axisLabel: {
          show: false
        }
      };
      option.series = [
        {
          name: '运输量',
          type: 'line',
          coordinateSystem: 'polar',
          data: currentData.value.map(item => item.value),
          smooth: true,
          symbol: 'circle',
          symbolSize: 12,
          lineStyle: {
            width: 4,
            color: '#37A2FF',
            shadowBlur: 15,
            shadowColor: 'rgba(55, 162, 255, 0.5)'
          },
          itemStyle: {
            borderWidth: 2,
            borderColor: '#fff',
            color: '#37A2FF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(55, 162, 255, 0.5)' },
              { offset: 1, color: 'rgba(55, 162, 255, 0)' }
            ])
          },
          emphasis: {
            lineStyle: {
              width: 5,
              shadowBlur: 20,
              shadowColor: 'rgba(55, 162, 255, 0.7)'
            }
          }
        },
        {
          name: '过渡点',
          type: 'scatter',
          coordinateSystem: 'polar',
          symbol: 'circle',
          symbolSize: 10,
          itemStyle: {
            color: '#FFBF00',
            borderWidth: 2,
            borderColor: '#fff'
          },
          data: currentData.value.map(item => null),
          animationDuration:3000
        }
      ];
      break;
  }

  chartInstance.setOption(option, true);
  highlightSelected();
};

const highlightSelected = () => {
  if (!chartInstance) return;
    
  chartInstance.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: selectedIndexes.value[0] || -1
  });
};

const switchChartType = () => {
  const types = ['pie', 'bar', 'line'];
  const currentIndex = types.indexOf(currentChartType.value);
  const nextIndex = (currentIndex + 1) % types.length;
  currentChartType.value = types[nextIndex];
  updateChart();
};

const startDataSwitching = () => {
  clearInterval(intervalId);
  intervalId = setInterval(switchChartType, 3000);
};

const handleResize = () => {
  chartInstance?.resize();
};

onMounted(async () => {
  await fetchEntryVolumeRatio();
  initChart();
  startDataSwitching();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  clearInterval(intervalId);
  chartInstance?.dispose();
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="less">
.chart-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-main {
  width: 100%;
  height: 100%;
}

.color-legend {
  position: absolute;
  right: 10px;
  bottom: 10px;
  display: flex;
  gap: 8px;
  padding: 8px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
}

.color-block {
  width: 24px;
  height: 24px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.2s ease;

  &:hover {
    transform: scale(1.2);
    box-shadow: 0 0 8px currentColor;
  }

  &.selected {
    outline: 2px solid #00bfff;
    box-shadow: 0 0 12px rgba(0, 191, 255, 0.7);
  }
}

.color-fill {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  
  .company-initial {
    color: white;
    font-weight: bold;
    font-size: 12px;
    text-shadow: 0 0 3px rgba(0, 0, 0, 0.8);
    user-select: none;
  }
}

@media (max-width: 768px) {
  .color-legend {
    right: 5px;
    bottom: 5px;
    gap: 6px;
    padding: 6px;
  }

  .company-initial {
    font-size: 10px;
  }

  .color-block {
    width: 20px;
    height: 20px;
  }
}
</style>